package com.itheima.demo4;

import java.util.List;
import java.util.Random;

/**
 * 磊哥：要返回结果去统计哪个线程的总金额多与少，所以应该实现Callable接口来做
 */
public class PeopleThread extends Thread{
    private List<Integer> moneys;
    //每个线程抢的总金额
    private int totalMoney;
    public PeopleThread(List<Integer> moneys, String name) {
        super(name);        //这就是线程的名字
        this.moneys = moneys;
    }
    private Random r = new Random();

    @Override
    public void run() {
        //每个线程准备抢红包的时候都等一会，让别的线程也创建好。减少先创建的线程抢的红包最多的这种事情
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        // 100个线程来抢钱。
        while (true){
            //取各个线程的名字
            String name = Thread.currentThread().getName();

            //竞争同一个集合，给集合加锁
            synchronized (moneys) {
                if (moneys.size() == 0) {
                    break;
                }
                // 取红包给当前这个人线程，并且从红包集合中删除
                int money = moneys.remove(r.nextInt(moneys.size()));
                System.out.println(name + "抢到：" + money);
                //不断累加每个线程各自的总红包金额
                totalMoney += money;
                try {
                    //模拟抢红包慢一点
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public int getTotalMoney() {
        return totalMoney;
    }

    public void setTotalMoney(int totalMoney) {
        this.totalMoney = totalMoney;
    }
}
